console.inspectEnable = true;
import WebApp from 'webapp'
import { SocketServer } from './libs/socket_server'
import devManager from './libs/sddc_device'
import { ISimpleDevice } from './libs/sddc_device/type'
import { ICallBack } from './interfaces/api.interface'
import { socket, sockName } from 'edgeros:socket';

const app = WebApp.createApp()
app.use(WebApp.static('../public'))

let acDev = null; // 场景空调设备
let acTemp = 26 // 场景空调设备温度

let acDev_model_control = null;
let acDev_tempre_control = null;
let acDev_gas = null;
let acDev_weather = null;


//存储前端变量数据
let interval_people = true; //是否有人， 默认为有人
let inner_tempre = 25;      //室内温度
let Switch = "open";        //默认初始为开启空调指令

let Model = 0;     //模式默认为自动

let switch_speed = 1;       //风速档位，默认为1
let switch_power = false;   //强劲档位 默认为关闭
let switch_sweep = false;   //扫风档位 默认为手动
let switch_light = true;    //灯光模式 默认为开

let settingTempre = 25;     //设定的温度
let restTime = 0;           //定时剩余分钟数
                            //后期考虑将其挂载到后端实现

let interval_off = 30;      //无人多少分钟后关闭空调
let autoClose = false;      //无人自动关机开关
let openClose = false;      //开机自动关窗
let position = 0;           //初始位置  0表示完全关闭

let temp_gate = false;      //是否启用温度阈值  默认不启用
let max_tempre = 30;        //上限温度
let min_tempre = 10;        //下限温度
let switch_settime = false; //是否启用定时模式
let alert_level = 0;        //警报等级
let setting_alert_level = 3;//默认警报等级

let devid_wether;
let devid_model_control;
let devid_tempre_control;



const io = new SocketServer(app)
io.on('connection', (socket) => {
  // 同步页面数据
  socket.on('init', (cb) => {
    if (typeof cb !== 'function') {
      return io.emitRoomMessage(socket.id, 'error', '参数错误！')
    }
    cb({devid: acDev? acDev.devid : '', temp: acTemp})
  })

  // 获取设备列表
  socket.on('device-list', (cb: (data: ISimpleDevice[]) => void) => {
    if (typeof cb !== 'function') {
      return io.emitRoomMessage(socket.id, 'error', '参数错误！');
    }
    cb(devManager.getDeviceList());
  })

  // 选择设备
  socket.on('select-device', (devid: string, cb: ICallBack) => {
    if (!devid || typeof cb !== 'function') {
      return io.emitRoomMessage(socket.id, 'error', '参数错误！')
    }
    if (acDev && acDev.devid == devid) {
      return
    }
    generateDevController(devid).then(() => {
      cb({result: true, message: '操作成功！'})
    }, () => {
      cb({result: false, message: '选中设备失败，请检查设备状态和应用权限！'})
    })
  })

  //向指定设备发送信息
  socket.on('model_change', (devid: string, data: any, cb: ICallBack) => {
    if (!devid || !data || typeof cb !== 'function') {
      return io.emitRoomMessage(socket.id, 'error', '参数错误！')
    }
    devManager.sendDeviceInfo(devid, data).then(() => {
      cb({result: true, message: '操作成功！'})
    }, () => {
      cb({result: false, message: '操作失败！'})
    })
  })

  //更新后端变量
  socket.on("update_var", (data: any, cb: ICallBack)=>{
    if(data.interval_people!=undefined)  interval_people = data.interval_people;
    if(data.inner_tempre)     inner_tempre = data.inner_tempre;
    if(data.Switch)           Switch = data.Switch;
    if(data.Model)            Model = data.Model;
    if(data.switch_speed)     switch_speed = data.switch_speed;
    if(data.switch_light!=undefined)     switch_light = data.switch_light;
    if(data.switch_power!=undefined)     switch_power = data.switch_power;
    if(data.switch_sweep!=undefined)     switch_sweep = data.switch_sweep;
    if(data.settingTempre)    settingTempre = data.settingTempre;
    if(data.restTime)         restTime = data.restTime;
    if(data.interval_off)     interval_off = data.interval_off;
    if(data.autoClose!=undefined)  autoClose = data.autoClose;
    if(data.openClose!=undefined)  openClose = data.openClose;
    if(data.position)         position = data.position;
    if(data.temp_gate!=undefined) temp_gate = data.temp_gate;
    if(data.max_tempre)       max_tempre = data.max_tempre;
    if(data.min_tempre)       min_tempre = data.min_tempre;        
    if(data.switch_settime)   switch_settime = data.switch_settime;
    if(data.alert_level)      alert_level = data.alert_level;
    if(data.setting_alert_level!=undefined)  setting_alert_level = data.setting_alert_level;

    cb({result: true, message: "更新变量成功"})
  })
  //更新前端变量
  socket.on("load_var", (cb: ICallBack)=>{
    io.emitMessage("load", {
      interval_people,
      inner_tempre,
      Switch,
      Model,
      switch_speed,
      switch_light,
      switch_power,
      switch_sweep,
      settingTempre,
      restTime,
      interval_off,
      autoClose,
      openClose,
      position,
      temp_gate,
      max_tempre,
      min_tempre,
      setting_alert_level
    });

    cb({result: true, message: "更新变量成功"})
  })
  //获取设备的id变量
  socket.on("submit_devid", (data:any, cb:ICallBack)=>{
    devid_model_control = data.devid_model_control;
    devid_wether = data.devid_wether;
    devid_tempre_control = data.devid_tempre_control;
    cb({result: true, message: "提交 devid 成功"});
  })
})

// 构建设备控制对象
function generateDevController(devid: string) {
  if (devManager.getController(devid)) {
    return Promise.resolve(devManager.getController(devid));
  }
  return new Promise((resolve, reject) => {
    const dev = devManager.getDevice(devid);
    if (!dev) {
      return reject('no device.');
    }
    if (dev.type == 'weather') {
      devManager
        .generateController(devid)
        .then((controller) => {
          acDev_weather = dev;
          controller.on('message', (data) => {
            io.emitMessage("weather", data);
          });
          resolve(controller);
        })
        .catch(() => {
          reject(`no permission.`);
        });
    }else if (dev.type == 'model_control') {
      devManager
        .generateController(devid)
        .then((controller) => {
          acDev_model_control = dev;
          // controller.on('message', (data) => {
          
          // });
          resolve(controller);
        })
        .catch(() => {
          reject(`no permission.`);
        });
    }else if (dev.type == 'window') { //弃置
      devManager
        .generateController(devid)
        .then((controller) => {
          resolve(controller);
        })
        .catch(() => {
          reject(`no permission.`);
        });
    }else if (dev.type == 'gas') {
      devManager
        .generateController(devid)
        .then((controller) => {
          acDev_gas = dev;
          controller.on('message', (data) => {
            io.emitMessage("gas", data);
          }); 
          resolve(controller);
        })
        .catch(() => {
          reject(`no permission.`);
        });
    }else if (dev.type == 'tempre_control') {
      devManager
        .generateController(devid)
        .then((controller) => {
          acDev_tempre_control = dev;
          controller.on('message', (data) => {
            // io.emitMessage("gas", data);
          }); 
          resolve(controller);
        })
        .catch(() => {
          reject(`no permission.`);
        });
    }
  });
}

devManager.on('error', (msg) => {
  io.emitMessage('error', msg)
})
// 设备上线
devManager.on('join', (dev) => {
  generateDevController(dev.devid).then(()=>{
    io.emitMessage('device-list', devManager.getDeviceList())
    console.log(acDev_gas, dev);

    if (acDev_gas && dev.devid==acDev_gas.devid){
      io.emitMessage('join', dev);
    }else if(acDev_model_control && dev.devid==acDev_model_control.devid){
      io.emitMessage('join', dev);
    }else if(acDev_tempre_control && dev.devid==acDev_tempre_control.devid){
      io.emitMessage('join', dev);
    }else if(acDev_weather && dev.devid==acDev_weather.devid){
      io.emitMessage('join', dev);
    }
  });
  
})

// 设备掉线
devManager.on('lost', (dev) => {

  console.log(acDev_gas, acDev_model_control, acDev_tempre_control, acDev_weather);
  console.log(dev);

  io.emitMessage('device-list', devManager.getDeviceList())
  if (acDev_gas && dev.devid==acDev_gas.devid){

    io.emitMessage('lost', dev);

  }else if(acDev_model_control && dev.devid==acDev_model_control.devid){

    io.emitMessage('lost', dev);

  }else if(acDev_tempre_control && dev.devid==acDev_tempre_control.devid){

    io.emitMessage('lost', dev);

  }else if(acDev_weather && dev.devid==acDev_weather.devid){

    io.emitMessage('lost', dev);

  }
})

//定时关闭空调
setInterval(()=>{
  if(Switch=="close"&&switch_settime){    //目前空调为开启状态
    
    if(restTime>0){
      restTime--;
    }else{
      //restTime==0   表示关闭空调
      switch_settime = false;
      devManager.sendDeviceInfo(devid_model_control, {
        method: "set",
        data: {
          type: "1",
          channel: "off"
        }
      })
      Switch = "open"
      //更新前端显示
      io.emitMessage("update_switch",{
        Switch: "open"
      })
    }
  }else{
    restTime = 0;
  }
},1000);


//无人自动关闭空调监听
let interval_count = interval_off;
setInterval(() => {
  // console.log(Switch, interval_people, interval_count)
  if(Switch=="close" && autoClose==true&&(!interval_people)){
    
    interval_count--;

    if(interval_count<=0){
      // console.log("emit!");
      //发送控制报文
      devManager.sendDeviceInfo(devid_model_control, {
        method: "set",
        data: {
          type: "1",
          channel: "off"
        }
      })
      Switch = "open";
      //更新前端图标
      io.emitMessage("update_switch",{
        Switch: "open"
      })
      interval_count = interval_off;
    }
  }else{
    interval_count = interval_off;
  }
}, 1000);



//监听温度阈值
setInterval(() => {
  if(temp_gate&&(Switch=="open")){
    if((inner_tempre>max_tempre)||(inner_tempre<min_tempre)){
      //发送开启空调报文
      devManager.sendDeviceInfo(devid_model_control, {
        method: "set",
        data: {
          type: "1",
          channel: "on"
        }
      })
      Switch = "close";
      //若同时启动开机自动关窗，发送关闭窗户报文
      if(openClose){
        devManager.sendDeviceInfo(devid_model_control, {
          method: "window",
          position: "100"
        })
        //更新前端信息
        io.emitMessage("update_window", {
          position: 100
        })
      }
      //更新前端信息
      io.emitMessage("update_switch", {
        Switch: "close"
      })
    }
  }
}, 3000);


//到达警报等级开机并切换模式为通风
setInterval(()=>{
  if(alert_level>=setting_alert_level){
    if(Switch=="open"){
    //开机
    Switch = "close";
    devManager.sendDeviceInfo(devid_model_control, {
      method: "set",
      data: {
        type: "1",
        channel: "on"
      }
    })
    }
    //开窗
    position = 100;
    devManager.sendDeviceInfo(devid_model_control, {
      method: "window",
      position: "100"
    })
    //切换模式为通风
    Model = 4;
    devManager.sendDeviceInfo(devid_model_control, {
      method: "set",
      data: {
        type: "3",
        model: "wind"
      }
    })

    //更新前端信息
    io.emitMessage("update_window", {
      position: 100
    })
    io.emitMessage("update_switch", {
      Switch: "close"
    })
    io.emitMessage("update_wind_model");
  }
},5000)

app.start()
require('iosched').forever()
